package fr.axones.pocketagile.ui.controler.command.account
{	
	import fr.axones.pocketagile.services.remote.AccountService;
	import fr.axones.pocketagile.services.remote.AuthenticationService;
	import fr.axones.pocketagile.ui.controler.Controler;
	import fr.axones.pocketagile.ui.view.authentication.AuthenticationEvent;
	import fr.axones.pocketagile.ui.view.main.account.AccountEvent;
	
	import mx.rpc.AsyncToken;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;

	public class AccountUpdateCommand
	{
		[Inject(id='accountService')]
		public var accountService:AccountService;
		
		[Inject(id='controler')]
		public var controler:Controler;
		
		public static const SUCCESS:String = "success";
		
		public static const ERROR_UNKNOW:String = "unknow";
		public static const ERROR_EMAIL_USED:String = "email.use";
		public static const ERROR_CONNECTION:String = "connection";
		
		public function AccountUpdateCommand()
		{
		}
		
		[Command(selector="updateUser")]
		public function execute(event:AccountEvent):AsyncToken
		{						
			return accountService.updateUser(event.user);
		}
		
		[CommandResult(selector="updateUser")]
		public function result(result:ResultEvent,event:AccountEvent):void
		{										
			if(result.result.status == 200)
			{
				controler.throwSuccess(SUCCESS,null,result.result.status);
			}
			else if(result.result.status == 409)
			{
				controler.throwError(ERROR_EMAIL_USED,null,1);
			}
			else
			{
				controler.throwError(ERROR_UNKNOW,null,1);
			}
		}
		
		[CommandError(selector="updateUser")]
		public function fault(fault:FaultEvent,event:AccountEvent):void
		{
			controler.throwError(ERROR_CONNECTION,null,0);
		}
	}
}